package com.example.roam.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.roam.R;
import com.example.roam.model.gson.User;
import com.example.roam.ui.adpter.InformationGenderAdapter;
import com.example.roam.ui.adpter.InformationNatureAdapter;
import com.example.roam.api.Api;
import com.example.roam.api.HttpUpload;
import com.example.roam.model.gson.InformationHead;
import com.example.roam.utils.Constans;
import com.example.roam.utils.DBHelper;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.StatusBarUtils;
import com.google.android.material.imageview.ShapeableImageView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Illustration
 *
 * @author dengqing
 * @time 2021/10/17
 * @function 用户头像，用户名，虚拟人物性别，虚拟人物性别标签
 */

public class InformationActivity extends AppCompatActivity {
    private EditText et_name;//用户昵称
    private Button btn_confirm;//确认按钮
    private ShapeableImageView img_head;//用户头像框
    private ImageView img_back;//返回按钮
    private GridView gridView_nature;
    private GridView gridView_gender;
    private List<Integer> list_gender;
    private List<String> list_nature;
    private InformationNatureAdapter adapter_nature;
    private InformationGenderAdapter adapter_gender;
    private int head_select = 1;//头像选择
    int naturePosition = 0;
    int genderPosition = 0;
    public static final int REQUEST_CHARACTER = 2;//跳转的虚拟人物界面选择请求码
    public static final int REQUEST_HEAD = 1;//跳转的头像选择请求码
    private String name = "蜀道旅客";//用户昵称
    private String gender = "man", nature = "lively";//虚拟人物形象的性别和性格标签
    private Retrofit retrofit;
    private static final String TAG = "InformationActivity";
    private boolean isUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色

        Intent intent = getIntent();
        isUpdate = intent.getBooleanExtra("isUpdate", false);
        findById();//初始化组件
        initNature();
        initGender();
        initData();//如果是更新！
    }

    private void initData(){
        if(isUpdate){
            et_name.setText(Constans.u_username);
            Glide.with(InformationActivity.this).load(Constans.u_head).into(img_head);
        }
    }

    private void initGender() {
        gridView_gender = findViewById(R.id.gridView_gender);
        list_gender = new ArrayList<>();
        list_gender.add(R.drawable.label_gender_woman);
        list_gender.add(R.drawable.label_gender_man);
        adapter_gender = new InformationGenderAdapter(this, list_gender);
        gridView_gender.setAdapter(adapter_gender);
        //gridView的点击事件
        gridView_gender.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //把点击的position传递到adapter里面去
                adapter_gender.changeState(position);
                genderPosition = position;
            }
        });
    }

    private void initNature() {
        gridView_nature = (GridView) findViewById(R.id.gridView_nature);
        //添加数据
        list_nature = new ArrayList<>();
        list_nature.add("活泼");
        list_nature.add("中性");
        list_nature.add("沉稳");
        adapter_nature = new InformationNatureAdapter(this, list_nature);
        gridView_nature.setAdapter(adapter_nature);
        //gridView的点击事件
        gridView_nature.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //把点击的position传递到adapter里面去
                adapter_nature.changeState(position);
                naturePosition = position;
            }
        });
    }

    //初始化组件
    private void findById() {
        et_name = findViewById(R.id.et_name);
        btn_confirm = findViewById(R.id.btn_confirm);
        img_head = findViewById(R.id.img_head);
        img_back = findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //头像选择监听方法
        img_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转头像选择界面
                Intent intent = new Intent(InformationActivity.this, InformationHeadActivity.class);
                startActivityForResult(intent, REQUEST_HEAD);
            }
        });

        //确认按钮监听方法
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                name = et_name.getText().toString();
                setGender(genderPosition);
                setNature(naturePosition);

                if (name.isEmpty()) {
                    name = "蜀道旅客";
                }
                //昵称为空或人物形象的标签为空
                if (name.isEmpty() || gender.isEmpty() || nature.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "昵称或虚拟人物标签不能为空", Toast.LENGTH_SHORT).show();
                    //单选框已经选择并且昵称不为空
                } else if ((!name.isEmpty()) && (!gender.isEmpty()) && (!nature.isEmpty())) { // 这里添加修改用户信息方法
                    updateUserInfo();
                    updateUserTableInformation(); // 设置的信息插入到SQLite中
//                    //跳转至主页面
                    Intent intent = new Intent(InformationActivity.this, CharacterActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("name", name);
                    bundle.putString("gender", gender);
                    bundle.putString("nature", nature);
                    intent.putExtras(bundle);
                    intent.putExtra("isUpdate",isUpdate);
                    startActivityForResult(intent, REQUEST_CHARACTER);
                    InformationActivity.this.finish();

                }
            }
        });
    }

    // 向服务器提交修改申请
    public void updateUserInfo(){
        Log.i(TAG, "updateUserInfo: u_head:"+Constans.u_head);
        retrofit = new Retrofit.Builder().baseUrl(HttpUtil.ADDRESS).build();
        retrofit.create(Api.class).updateUser(Constans.u_id,name,Constans.u_password,"","",Constans.u_head+"",1,1,1,HttpUtil.COOKIE).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(InformationActivity.this,"设置成功！",Toast.LENGTH_SHORT).show();
                    }
                });
                initConstants();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(InformationActivity.this,"修改失败！",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {         //头像选择结果返回
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_HEAD && resultCode == RESULT_OK) {
            head_select = data.getIntExtra("head_select", 1); // 1使用系统提供， 2使用相册
            String headPath = data.getStringExtra("headPath");
            switch (head_select) {
                case 1:
                    Glide.with(InformationActivity.this).load(Constans.u_head).into(img_head);
                    break;
                case 2:
                    Log.i(TAG, "onActivityResult: headPath:"+headPath);
                    postImage(headPath);
                    break;
            }
        }
    }

    public void postImage(String realFilePath){
        File file = new File(realFilePath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"),file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("uploadFile",file.getName(),requestBody);
        Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(HttpUtil.FILE_ADDRESS).build();
        retrofit.create(HttpUpload.class).uploadUserHeadImg(part).enqueue(new Callback<InformationHead>() {
            @Override
            public void onResponse(Call<InformationHead> call, Response<InformationHead> response) {
                String url = response.body().getData().getUrl();
                InformationActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(InformationActivity.this).load(url).into(img_head);
                        Constans.u_head = url;
                    }
                });
            }
            @Override
            public void onFailure(Call<InformationHead> call, Throwable t) {

            }
        });
    }

    public void initConstants(){
        Constans.u_username = name;
    }

    public void updateUserTableInformation() {
        DBHelper dbHelper = new DBHelper(InformationActivity.this, null, null, 1);
        SQLiteDatabase ds = dbHelper.getReadableDatabase();
        ContentValues contentValues = new ContentValues();
        // 资源类型的东西，获取int值后转化为string保存
        // 第一此插入信息，插入。用户头像，用户姓名
        contentValues.put("u_username", name);
        contentValues.put("head_select", head_select);
        Constans.u_username = name;
        Constans.head_select = head_select;
        ds.update("user", contentValues, "u_id = ?", new String[]{Constans.u_id + ""});
    }

    private void setNature(int naturePosition) {
        switch (naturePosition) {
            case 0:
                nature = "lively"; // 活泼
                break;
            case 1:
                nature = "neutral";  // 中性
                break;
            case 2:
                nature = "steady";  // 沉稳
                break;
        }

    }

    private void setGender(int genderPosition) {
        switch (genderPosition) {
            case 0:
                gender = "man";
                break;
            case 1:
                gender = "woman";
                break;
        }
    }

}
